package com.example.forum.services.impl;

import com.example.forum.common.ResultCode;
import com.example.forum.dao.MessageMapper;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void create(Long postUserId,Long receiveUserId,String content) {
        //  1. 参数校验
        if(postUserId == null || receiveUserId == null || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        //  1.1 校验 发送者 和 接受者 是否存在
        User postUser = userMapper.selectByPrimaryKey(postUserId);
        User receiveUser = userMapper.selectByPrimaryKey(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1 ||
                postUser == null || postUser.getDeleteState() == 1 ) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        //  1.2 校验 发送者 是否与 接受者 相同
        if(postUserId.equals(receiveUserId)) {
            log.warn(ResultCode.FAILED_CREATE.toString() + "不能给自己发私信");
            throw new ApplicationException(ResultCode.FAILED_CREATE.getMessage());
        }

        //  2. 组装数据
        Message message = new Message();
        message.setPostUserId(postUserId);
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);

        //  3. 调用mapper
        int row = messageMapper.insertSelective(message);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ". 新增私信失败");
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }
        log.info("新增私信成功. ");
    }

    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        //  调用mapper
        Integer count = messageMapper.selectUnreadCount(receiveUserId);

        return count;
    }

    @Override
    public List<Message> selectAllById(Long receiveUserId) {
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        //  调用mapper
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);
        return messages;
    }

    @Override
    public Message selectById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        //  调用mapper
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS.getMessage());
        }
        return message;
    }

    @Override
    public void updateStateById(Long id,Byte state) {
        if(id == null || id <= 0 ||
                state != 0 && state != 1 && state != 2) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }


        //  检验私信是否存在
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS.getMessage());
        }

        //  封装对象
        Message updateMessage = new Message();
        updateMessage.setId(id);
        //  私信状态是已回复时，状态不再变
        if(message.getState() != 2) {
            updateMessage.setState(state);
        }
        updateMessage.setUpdateTime(new Date());

        //  调用mapper
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ". 新增私信失败");
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }
        log.info("更新私信状态成功. message.id = " + message.getId() +
                ". message.state = " + message.getState());
    }

    @Override
    public void reply(Long replyId,Long postUserId,Long receiveUserId,String content) {
        if(replyId == null || replyId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        //  校验要回复的私信是否存在
        Message exitsMessage = selectById(replyId);
        if(exitsMessage == null || exitsMessage.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS.getMessage());
        }

        //  新增回复私信
        create(postUserId,receiveUserId,content);

        //  更改私信状态
        updateStateById(replyId, (byte) 2);
    }
}
